﻿using AutoMapper;
using MediatR;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using SmartProduction.Domain.yjh;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Write.API.Application.Commands.MaterialLists;

namespace SmartProduction.Write.API.Application.CommandHandlers.MaterialLists
{
    /// <summary>
    /// 物料删除命令处理
    /// </summary>
    public class MaterDeleteCommandHandler:IRequestHandler<MaterListDeleteCommand,APIResult<object>>
    {
        /// <summary>
        /// 物料仓储
        /// </summary>
        private readonly IBaseRepository<MaterialList> materRep;
        /// <summary>
        /// mapper映射
        /// </summary>
        private readonly IMapper mapper;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="materRep">物料仓储</param>
        /// <param name="mapper">mapper</param>
        public MaterDeleteCommandHandler(IBaseRepository<MaterialList> materRep, IMapper mapper)
        {
            this.materRep = materRep;
            this.mapper = mapper;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<object>> Handle(MaterListDeleteCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();

            var entity = materRep.GetAll().Result.First(x => x.MaterialId == request.materialId);

             entity.IsDeleted = true;
            var r=materRep.UpdateAsync(entity).Result;
            if (r > 0)
            {
                LogModel logModel = new LogModel();
                logModel.CreateDate = DateTime.Now;
                logModel.CreatePerson = "YJH";
                logModel.LoginThing = "正在删除物料";
                result.Code = APIEnums.删除成功;
                result.Msg=APIEnums.删除成功.ToString();
                result.data=r;
            }
            else
            {
                result.Code = APIEnums.删除失败;
                result.Msg = APIEnums.删除失败.ToString();
                result.data = r;
            }
            return await Task.FromResult(result);
             
        }
    }
}
